# 本环境在flask 2.2.2
# flask_restx 不支持2.2.2 做个记录

import os
from flask import Flask, flash, request, redirect, url_for, render_template
from werkzeug.utils import secure_filename
from flask import send_from_directory
from werkzeug.datastructures import FileStorage
from flask_restx import Resource, Api, reqparse

BASE_DIR = os.path.dirname(os.path.realpath(__file__))
UPLOAD_FOLDER = os.path.join(BASE_DIR, 'media')
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}

api = Api()
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
api.init_app(app)

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@api.route('/upfile')
class Upload(Resource):

    @staticmethod
    def allowed_file(filename):
        return '.' in filename and \
               filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('file', required=True, type=FileStorage, location='files')
        parser.add_argument('title', type=FileStorage, location='files')
        args = parser.parse_args()
        file = args['file']  # 获取文件对象
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)  # 校验文件名称合法
            print(filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return {
                'msg': 'success',
                'url': f'/images/{filename}/',
            }
        else:
            return {
                'msg': '文件格式不支持'
            }

if __name__ == '__main__':
    app.run()